package com.valkyries.jhhj.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.google.code.kaptcha.Producer;
import com.valkyries.jhhj.common.Result;
import com.valkyries.jhhj.constant.CacheConstants;
import com.valkyries.jhhj.constant.Constants;
import com.valkyries.jhhj.utils.IdUtils;
import com.valkyries.jhhj.utils.RedisCache;
import jakarta.annotation.Resource;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 */
@RestController
@RequestMapping("/sys/captcha")
public class CaptchaController {
    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    /**
     * 生成验证码
     */
    @SaIgnore
    @GetMapping("/getCaptcha")
    public Result getCaptchaImg() {
        //生成验证码文本
        String text = captchaProducerMath.createText();
        String capStr = text.substring(0 , text.lastIndexOf("@"));
        String code = text.substring(text.lastIndexOf("@") + 1);
        //生成验证码图片
        BufferedImage captchaImg = captchaProducerMath.createImage(capStr);
        //保存验证码
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        redisCache.setCacheObject(verifyKey, code , Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
//        System.out.println("生成的验证码是:" + text);
//        System.out.println("生成的uuid是:" + uuid);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(captchaImg, "jpg", os);
        } catch (IOException e) {
            return Result.error(e.getMessage());
        }
        Result res = Result.ok();
        res.put("uuid", uuid);
        res.put("img", Base64.encodeBase64String(os.toByteArray()));
        return res;
    }
}
